package io.zerous.engine.ui

import android.graphics.Color
import io.zerous.engine.Zex
import io.zerous.engine.math.*
/**
 * Created by Zerous on 2018/9/23.
 */
class Rocker(val position: Vector2, val radius: Float) {
    val base = Circle(Vector2(position), radius)
    val roll = Circle(Vector2(position), radius / 2f)

    var focusOn = false
    var focusPointer = -1;

    var touchPoint = Vector2()

    fun getDirection(): Vector2 {
        val original = roll.position.copy() - base.position
        return original / radius
    }

    fun update() {
        for (i in 0..5) {
            if (!focusOn and Zex.input.isTouchDown(i) and base.includes(Zex.input.getTouchPoint(i))) {
                focusOn = true
                focusPointer = i;
            }
        }

        if (focusOn) {
            if (!Zex.input.isTouchDown(focusPointer)) {
                focusOn = false
                focusPointer = -1
            }

            touchPoint.set(Zex.input.getTouchPoint(focusPointer))

            if ((touchPoint.copy() - position).len() < radius) {
                roll.position.set(touchPoint)
            } else {
                roll.position.set((touchPoint - position).normalize() * radius + position)
            }
        } else {
            roll.position.set(base.position)
        }
    }

    fun draw() {
        Zex.graphics.drawCircle(base, color = if (focusOn) Color.GREEN else Color.RED, alpha = 0x50)
        Zex.graphics.drawCircle(roll, alpha = 0x50)
    }
}